import {
  Controller,
  Get,
  Post,
  Query,
  Body,
  Patch,
  Delete,
  Headers,
  UseFilters,
  Param,
  UnauthorizedException,
  ParseIntPipe,
  UseGuards,
} from '@nestjs/common';
import { UserService } from './user.service';
import { ApiTags } from '@nestjs/swagger';
import { getUserDto } from './dto/get-user.dto';
import { TypeormFilter } from 'src/filters/typeorm.filter';
import { User } from './user.entity';
import { AdminGuard } from '../guards/admin.guard';
import { JwtGuard } from '../guards/jwt.guard';

@ApiTags('用户模块')
@Controller('user')
@UseFilters(new TypeormFilter())
@UseGuards(JwtGuard)
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  @UseGuards(AdminGuard)
  getUsers(@Query() query: getUserDto): Promise<any> {
    return this.userService.findAll(query);
  }

  @Post()
  createUser(@Body() userData: User): Promise<any> {
    return this.userService.createUser(userData);
  }

  @Delete('/:id')
  removeUser(@Query('id', ParseIntPipe) id: any): Promise<any> {
    return this.userService.remove(id);
  }

  @Patch('/:id')
  updateUser(
    @Body() dto: any,
    @Param('id') id: number,
    @Headers('Authorization') headers: any,
  ): Promise<any> {
    if (id === headers) {
      const user = dto as User;
      return this.userService.update(id, user);
    } else {
      throw new UnauthorizedException();
    }
  }
}
